package com.haust.community.event;

import com.alibaba.fastjson.JSONObject;
import com.haust.community.pojo.DiscussPost;
import com.haust.community.pojo.Message;
import com.haust.community.service.DiscussPostService;
import com.haust.community.service.ElasticSearchService;
import com.haust.community.service.FileUploadService;
import com.haust.community.service.MessageService;
import com.haust.community.utils.CommunityConstant;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;

/**
 * @Auther: csp1999
 * @Date: 2020/11/29/13:47
 * @Description: 事件消费者
 */

@Component
public class EventConsumer implements CommunityConstant {

    private static final Logger logger = LoggerFactory.getLogger(EventConsumer.class);

    @Autowired
    private MessageService messageService;

    @Autowired
    private ElasticSearchService elasticSearchService;

    @Autowired
    private DiscussPostService discussPostService;

    // wk 工具的路径(生成图片)
    @Value("${wk.image.command}")
    private String wkImageCommand;

    // 图片存储位置
    @Value("${wk.image.storage}")
    private String wkImageStorage;

    @Autowired
    private ThreadPoolTaskScheduler taskScheduler;

    @Autowired
    private FileUploadService fileUploadService;

    /**
     * 消费图片分享事件
     *
     * @param record
     */
    @KafkaListener(topics = TOPIC_SHARE)
    public void handleShareMessage(ConsumerRecord record) {
        if (record == null || record.value() == null) {
            logger.error("消息的内容为空!");
            return;
        }

        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        if (event == null) {
            logger.error("消息格式错误!");
            return;
        }

        String htmlUrl = (String) event.getData().get("htmlUrl");// 文件url
        String fileName = (String) event.getData().get("fileName");// 文件名称
        String suffix = (String) event.getData().get("suffix");// 后缀

        // cmd 命令
        String cmd = wkImageCommand + " --quality 75 "
                + htmlUrl + " " + wkImageStorage + "/" + fileName + suffix;
        try {
            // 操作系统执行cmd 命令
            Runtime.getRuntime().exec(cmd);
            logger.info("生成长图成功: " + cmd);
        } catch (IOException e) {
            logger.error("生成长图失败: " + e.getMessage());
        }

        // 启用定时器,监视该图片,一旦生成成功了,就把该图片上传至OSS.
        UploadTask task = new UploadTask(fileName, suffix);
        Future future = taskScheduler.scheduleAtFixedRate(task, 500);
        task.setFuture(future);
    }

    /**
     * 上传任务内部类
     */
    class UploadTask implements Runnable {

        // 文件名称
        private String fileName;
        // 文件后缀
        private String suffix;
        // 启动任务的返回值
        private Future future;
        // 开始时间
        private long startTime;
        // 上传次数
        private int uploadTimes;

        public UploadTask(String fileName, String suffix) {
            this.fileName = fileName;
            this.suffix = suffix;
            this.startTime = System.currentTimeMillis();
        }

        public void setFuture(Future future) {
            this.future = future;
        }

        @Override
        public void run() {
            // 生成失败
            if (System.currentTimeMillis() - startTime > 30000) {
                logger.error("执行时间过长,终止任务:" + fileName);
                future.cancel(true);
                return;
            }
            // 上传失败
            if (uploadTimes >= 3) {
                logger.error("上传次数过多,终止任务:" + fileName);
                future.cancel(true);
                return;
            }

            String path = wkImageStorage + "/" + fileName + suffix;
            File file = new File(path);
            if (file.exists()) {
                logger.info(String.format("开始第%d次上传[%s].", ++uploadTimes, fileName));
                try {
                    String upload = fileUploadService.upload(file);
                    logger.info(String.format("第%d次上传成功[%s].", uploadTimes, fileName));
                    future.cancel(true);
                } catch (Exception e) {
                    logger.info(String.format("第%d次上传失败[%s].", uploadTimes, fileName));
                }
            } else {
                logger.info("等待图片生成[" + fileName + "].");
            }
        }

    }

    /**
     * 消费者订阅主题，消费：
     * TOPIC_COMMENT评论事件
     * TOPIC_LIKE点赞事件
     * TOPIC_FOLLOW加关注事件
     * 就是通过 @KafkaListener(topics = {}) 注解实现的
     *
     * @param record
     */
    @KafkaListener(topics = {TOPIC_COMMENT, TOPIC_LIKE, TOPIC_FOLLOW})
    public void handleCommentMessage(ConsumerRecord record) {
        if (record == null || record.value() == null) {
            logger.error("消息的内容为空!");
            return;
        }

        // 将订阅的消息内容转换成 Event 对象
        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        if (event == null) {
            logger.error("消息格式错误!");
            return;
        }

        // 发送站内通知
        Message message = new Message();
        // 通知来自系统用户
        message.setFromId(SYSTEM_USER_ID);
        // 通知发送到实体(帖子)用户的id
        // 比如A 给 B的帖子点赞,B 会收到系统提示 A 给其点赞了
        message.setToId(event.getEntityUserId());
        // 会话主题
        message.setConversationId(event.getTopic());
        // 通知消息发送日期
        message.setCreateTime(new Date());
        // 通知消息的其他内容
        Map<String, Object> content = new HashMap<>();
        // 触发通知的用户id 即A给B点赞后，触发用户为A
        content.put("userId", event.getUserId());
        // 触发通知的实体类型,比如 A给B 发布的xx 帖子点赞,xx 就是触发通知的实体，类型是帖子
        content.put("entityType", event.getEntityType());
        // 触发通知的实体id，如果实体类型是帖子，实体id就是帖子的id
        content.put("entityId", event.getEntityId());

        if (!event.getData().isEmpty()) {
            for (Map.Entry<String, Object> entry : event.getData().entrySet()) {
                // 将 event中的data这个map集合的key和value ，依次存入 content这个map集合中去
                content.put(entry.getKey(), entry.getValue());
            }
        }

        // 将content 放入 message
        message.setContent(JSONObject.toJSONString(content));
        // 保存message 内容
        messageService.addMessage(message);
    }

    /**
     * 消费者订阅主题，消费：
     * TOPIC_PUBLISH发帖事件
     *
     * @param record
     */
    @KafkaListener(topics = {TOPIC_PUBLISH})
    public void handlePublishMessage(ConsumerRecord record) {
        // 判空
        if (record == null || record.value() == null) {
            logger.error("消息的内容为空!");
            return;
        }

        // 类型转换并判空
        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        if (event == null) {
            logger.error("消息格式错误!");
            return;
        }

        // 先从数据库中查询帖子内容
        DiscussPost post = discussPostService.findDiscussPostById(event.getEntityId());
        // 然后将查询的内容存入ES
        elasticSearchService.saveDiscussPost(post);
    }

    /**
     * 消费删帖事件
     *
     * @param record
     */
    @KafkaListener(topics = {TOPIC_DELETE})
    public void handleDeleteMessage(ConsumerRecord record) {
        if (record == null || record.value() == null) {
            logger.error("消息的内容为空!");
            return;
        }

        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        if (event == null) {
            logger.error("消息格式错误!");
            return;
        }

        elasticSearchService.deleteDiscussPost(event.getEntityId());
    }
}
